package com.hjx.leetcode;

import java.util.concurrent.Semaphore;

/**
 * 控制线程的执行顺序
 * 解法2、Semaphore 实现一个等一个的效果,
 * 先让许可为0，那么所有线程在申请许可是就会进入park状态
 * 当first 执行完 c1 提供一个许可， second的执行线程得到许可，开始执行
 * 同理 执行完成后向third 提供一个许可，third可以继续执行，这就完成了不同线程的有序执行
 */
class LeetCode_1114_solution2 {

    public Semaphore c1 = new Semaphore(0);
    public Semaphore c2 = new Semaphore(0);

    public void first(Runnable printFirst) throws InterruptedException {

        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        //开启second
        c1.release(1);
    }

    public void second(Runnable printSecond) throws InterruptedException {

        c1.acquire();
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        //开启third
        c2.release(1);

    }

    public void third(Runnable printThird) throws InterruptedException {

        c2.acquire();
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
    }

}
